package com.xiao.kmss.util;

/**
 * 图片链接下载后，转成Base64 格式
 * Author: YQH
 * Date: 2025/10/21
 */
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

public class WxImg2Base64 {

    public static String toBase64(String wxUrl) throws Exception {
        URL url = new URL(wxUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Referer", "https://mp.weixin.qq.com");
        conn.setConnectTimeout(5_000);
        conn.setReadTimeout(10_000);

        try (InputStream in = conn.getInputStream();
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            byte[] buf = new byte[4096];
            int n;
            while ((n = in.read(buf)) != -1) out.write(buf, 0, n);

            byte[] data = out.toByteArray();
            // JDK 8+
            return "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(data);
        }
    }

    // 快速测试
    public static void main(String[] args) throws Exception {
        String url = "http://mmecoa.qpic.cn/sz_mmecoa_jpg/ibbjiazxVbibLgfc57937ib8GRnIS08TBkaeSopGicLBhicQg61JkicrC3eiblraE4VhQVD34HSENHkx54zicR4sqibJGtaQ/0?wx_fmt=jpeg";
        String base64 = toBase64(url);
        System.out.println(base64); // 打印前 100 字符
    }
}
